﻿using System;
using C556Backside.Commands.Share;
using C556Backside.Models;
using C556Backside.Services;
using C556Backside.ViewModel.Share;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace C556Backside.Controllers;

[ApiController]
[EnableCors("CorsPolicy")]
[Route("Share")]
public class ShareController
{
    public C556DBContext DBContext { get; set; }
    public ShareController(C556DBContext c556DBContext)
    {
        DBContext = c556DBContext;
    }
    [HttpGet]
    [Route("GetReviewByActivityID")]
    public List<ActivityReviewModel> GetReviewByActivityID([FromQuery] CGetReviewByActivityID data)
    {
        return DBContext.ActivityReviews.Include(o => o.VAandVRelationships).ThenInclude(o => o.VoluntaryModel).Where(e => e.VAandVRelationships.ActivityID == data.ActivityID).ToList();
    }
    [HttpGet]
    [Route("GetAllActivityByActivityType")]
    public List<GetAllActivityByActivityTypeModel> GetAllActivityByActivityType()
    {
        var list = new List<GetAllActivityByActivityTypeModel>();
        foreach (var tItem in DBContext.ActivityTypeModels.Include(e => e.VoluntaryActivities.Where(o => !o.IsDelete)))
        {
            var model = new GetAllActivityByActivityTypeModel() { Name = tItem.ActivityTypeName };
            if (tItem.VoluntaryActivities == null)
            {
                model.Value = 0;
            }
            else
            {
                model.Value = tItem.VoluntaryActivities.Count;
            }
            list.Add(model);
        }
        return list;
    }

    [HttpGet]
    [Route("GetActivityByActivityName")]
    public List<VGetActivityByActivityName> GetActivityByActivityName([FromQuery] CGetActivityByActivityName model)
    {
        var list = DBContext.VoluntaryActivities.Where(o => o.ActivityName.Contains(model.ActivityPartName) && o.IsDelete == false).Select(e => new { e.ActivityName }).Select(e => new VGetActivityByActivityName { ActivityName = e.ActivityName }).ToList();
        return list;
    }

    [HttpPost]
    [Route("AnalyseActivity")]
    public List<VAnalyseActivity> AnalyseActivity([FromBody] CAnalyseActivity model)
    {
        var list = new List<VAnalyseActivity>();
        foreach (var item in model.IDs)
        {
            var activity = this.DBContext.VoluntaryActivities.Include(o => o.ActivityTypeModel).First(o => o.ActivityID == item);
            var r = list.SingleOrDefault(o => o.Name == activity.ActivityTypeModel.ActivityTypeName);
            if (r == null)
            {
                var n = new VAnalyseActivity { Name = activity.ActivityTypeModel.ActivityTypeName, Count = 1 };
                list.Add(n);
            }
            else
            {
                r.Count++;
            }
        }
        return list;
    }
}
